package com.example.myapp.RecordFragemt;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.fragment.app.Fragment;


import com.example.myapp.ADO.RecordAdopter;
import com.example.myapp.Listviewloading.MyFooterAdapter;
import com.example.myapp.Listviewloading.MyHeaderAdapter;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Record;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnFooterRefreshListener;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


//import android.support.v4.app.Fragment;


/**
 * A simple {@link Fragment} subclass.

 * create an instance of this fragment.
 */
public class Fragment1 extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SHOW_TEXT = "text";
    private String mContentText;
    private ListView listview;
    private   RecordAdopter adapter;
    private UltimateRefreshView mUltimateRefreshView;
    private   List<Record>  list=new ArrayList<>();
    private ShapeLoadingDialog shapeLoadingDialog;
    private int page = 0;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String updatatime="";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Recorddiushi();
                    break;
            }
        }
    };


    public Fragment1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment FootFragment1.
     */
    public static Fragment1 newInstance(String param1) {
        Fragment1 fragment = new Fragment1();
        Bundle args = new Bundle();
/**
 *   接收传来的param1赋值给ARG_SHOW_TEXT
 *
 */
        args.putString(ARG_SHOW_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         *   接收外面传来的param1赋值给AmContentText
         *
         */
        if (getArguments() != null) {
            mContentText = getArguments().getString(ARG_SHOW_TEXT);

        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        /**
         * 这里相当相当于Activity里面的onCreate函数 ，注意： rootView.
         */
        View rootView = inflater.inflate(R.layout.diushi, container, false);
        listview= rootView.findViewById(R.id.listview);
        mUltimateRefreshView = (UltimateRefreshView)rootView.findViewById(R.id.refreshView);
        mUltimateRefreshView.setBaseHeaderAdapter(new MyHeaderAdapter(getActivity()));
        /**底部上拉加载*/
        mUltimateRefreshView.setBaseFooterAdapter(new MyFooterAdapter(getActivity()));

        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);


        /**头部下拉刷新事件*/
        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {
                page = 0;
                /**
                 * 某个时间后
                 */
                try {
                    String createdAt = updatatime;
                    Date date = new Date(System.currentTimeMillis());
                    updatatime= simpleDateFormat.format(date);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date createdAtDate = sdf.parse(createdAt);
                    BmobDate bmobCreatedAtDate = new BmobDate(createdAtDate);
                    BmobQuery<Record> categoryBmobQuery = new BmobQuery<>();
                    categoryBmobQuery.addWhereEqualTo("key","丢失");
                    categoryBmobQuery.addWhereGreaterThan("createdAt", bmobCreatedAtDate);
                    categoryBmobQuery.setLimit(5); // 限制最多10条数据结果作为一页
                    categoryBmobQuery.include("posts,user");
                    categoryBmobQuery.order("-orderTime");
                    categoryBmobQuery.findObjects(new FindListener<Record>() {
                        @Override
                        public void done(List<Record> object, BmobException e) {
                            if (e == null) {
                                Log.w("aaaa", "刷新条数: "+ object.size());
                                if(object.size()>0){
                                    //说明有新文章
                                    list.clear();
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                    mUltimateRefreshView.onHeaderRefreshComplete();
                                }else {
                                    mUltimateRefreshView.onHeaderRefreshComplete();
                                }

                            } else {
                                Log.e("BMOB", e.toString());
                            }
                        }
                    });
                }catch (Exception e){

                }

            }
        });
        /**底部上拉加载事件*/
        mUltimateRefreshView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
            @Override
            public void onFooterRefresh(UltimateRefreshView view) {
                page++;
                BmobQuery<Record> query = new BmobQuery<>();
                query.addWhereEqualTo("key","丢失");
                query.setSkip(page*5); // 忽略前10条数据（即第一页数据结果）
                query.setLimit(5); // 限制最多10条数据结果作为一页
                //包含作者信息
                query.include("posts,user");
                query.order("-orderTime");
                query.findObjects(new FindListener<Record>() {
                    @Override
                    public void done(List<Record> object, BmobException e) {
                        if (e == null) {
                            if (object.size()>0){
                                list.addAll(object);
                                 adapter .notifyDataSetChanged();
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }else {
                                mUltimateRefreshView.onFooterRefreshComplete();
                            }
                        } else {
                            Log.e("aaaa","查询我的动态失败"+ e.getMessage());
                            mUltimateRefreshView.onFooterRefreshComplete();
                        }
                    }

                });



            }
        });



        return rootView;
    }

    //查询丢失
    private void Recorddiushi(){

        Date date = new Date(System.currentTimeMillis());
        updatatime= simpleDateFormat.format(date);
            BmobQuery<Record> query = new BmobQuery<Record>();
            User user = BmobUser.getCurrentUser(User.class);//查询自己
            //friend是User表中的字段，用来存储所有关注的用户
            query.addWhereEqualTo("key","丢失");
            //包含作者信息
            query.include("user,author");
            query.order("-orderTime");
            query.findObjects(new FindListener<Record>() {
                @Override
                public void done(List<Record> object, BmobException e) {
                    if (e == null) {
                        list=object;
                         adapter = new RecordAdopter(getActivity(),list);//NewAdapterDAO为自定义适配器
                        listview.setAdapter(adapter);
                        Log.w("aaaa", "丢失表成功！"+object.size());

                    } else {
                        Log.e("aaaa","失败"+ e.getMessage());

                    }

                }

            });

    }
    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(getActivity())
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }

}
